package com.anhry.www.safety.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;

import javax.servlet.ServletContext;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * 生成静态界面公用类
 * @author dongbin
 *
 */
public class CrateHTML {
	public static void crateHTML(ServletContext context,Map<String, Object> data, String templatePath, String targetHtmlPath) {
		try {
			Configuration freemarkerCfg = new Configuration();
			// 加载模版
			freemarkerCfg.setServletContextForTemplateLoading(context, "/");
			//freemarkerCfg.setDirectoryForTemplateLoading(new File(context.getRealPath("") + "/WEB-INF/template/"));
			freemarkerCfg.setEncoding(Locale.getDefault(), "UTF-8");
		
			// 指定模版路径
			Template template = freemarkerCfg.getTemplate(templatePath, "UTF-8");
			template.setEncoding("UTF-8");
			// 静态页面路径
			String htmlPath = context.getRealPath("") + "/" + targetHtmlPath;
			File htmlFile = new File(htmlPath);
			Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile), "UTF-8"));
			// 处理模版
			template.process(data, out);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}